var w = {
    open_close_btn : function(open) {
        if(open) {
            $("#submit_post").attr('disabled','disabled').removeClass('ui-button-lorange').addClass('ui-button-lwhite');
        } else {
            $("#submit_post").removeAttr('disabled').removeClass('ui-button-lwhite').addClass('ui-button-lorange');
        }
    },
    remove_link: function(content) {
        return content.replace(/<a.*?>.*?<\/a>/ig,"")
    },
    replace_var:function(){
        $("#preview").find('span').each(function(k,i){
            if(json_e_array[$(this).attr('data-code')]){
                $(this).text(json_e_array[$(this).attr('data-code')]);
            }
        });
    },
    set_preview:function(content){
        $("#preview").html(content);
        $("input[name='cformat']").val(content);
        this.replace_var();
    },
    get_default_tpl:function(did, pid, ptype){
        var that = this;
        $.get('/jq/jh/jh_front.php',{todo:'GetSMSTPL', did:did, pid:pid, ptype:ptype})
            .done(function(res){
                $("#sms_content").html(res);
                that.set_preview(that.remove_link(res));
            });
    }
};
$(document).ready(function() {
    var defaultTpl = $("div#defaultTpl").html(),
        did = $("input[name='did']").val();
    var getContents = function(){
        var content = w.remove_link( $("#sms_content").html());
        w.set_preview(content);
    };
    $(".tpl_variables").on('click','a.var',function(){
        var code = $(this).attr('data-code'),
            txt = $(this).attr('data-txt');
        fn_insertPos(txt, code);
        getContents();
    });
    $("a.del").live('click',function(){
        $(this).parent().remove();
        getContents();
    });
    $("#sms_content").bind('keyup change', getContents);

    $("select#prod_type").on('change', function(){
        w.get_default_tpl(did,0, $(this).val());
    });

    $("#pids").change(function(){
        var f = $(this).find('option:selected'),
            pname = f.attr('data-pname'),
            lid= f.val();
        if(lid==0) return;
        json_e_array['{pname}'] = pname;
        $("#choicedProd").text(pname);
        $.get('/jq/jh/jh_front.php',{todo:'GetSMSTPL', did:did, lid:lid})
            .done(function(res){
                $("#sms_content").html(res);
                w.set_preview(w.remove_link(res));
            });
    });

    $("#editLnk").on('click',function(){
        if($(this).hasClass('open')) {
            $(this).text('编辑短信模板');
            $("#edit_sms_tpl").hide();
            $(this).removeClass('open');
            w.open_close_btn(1);
        } else {
            $(this).addClass('open');
            $("#edit_sms_tpl").show();
            $(this).text('取消');
            w.open_close_btn(0);
        }
    });
	
	// 获取默认模板
	$("#getDefault").on('click',function(){ 
        //$("#sms_content").html('<span contenteditable="false" data-code="{pname}">[预定产品]</span>:<span contenteditable="false" data-code="{tnum}">[预定数量]</span>凭证号：<span contenteditable="false" data-code="{code}">[凭证号]</span>,游玩日期|有效期至|有效期:<span contenteditable="false" data-code="{begintime}">[游玩/入住时间]</span>,取票信息:<span contenteditable="false" data-code="{getaddr}">[取票信息]</span>,此为入园凭证,请妥善保管。<span contenteditable="false" data-code="{link}">[详情及二维码链接]<a href="javascript:" class="del">X</a></span>');
		$("#sms_content").html('凭证号:<span contenteditable="false" data-code="{code}">[凭证号]</span>,您已成功购买了<span contenteditable="false" data-code="{pname}">[预定产品]</span><span contenteditable="false" data-code="{tnum}">[预定数量]</span>,<span contenteditable="false" data-code="{begintime}">[游玩/入住时间]</span>,<span contenteditable="false" data-code="{getaddr}">[取票信息]</span>,此为入园凭证,请妥善保管。<span contenteditable="false" data-code="{link}">详情及二维码:[详情及二维码链接]<a href="javascript:" class="del">X</a></span>');
    });
	
	// 重置短信模板
	$("#resetTpl").on("click",function(){
		$("#sms_content").html($(".tmpSms").val());
	});
	
    $("input[name='tpl_type']").on('click',function(){
        var v = $(this).val();
        if(v==2) {
            $("#prod_choice").show().find('select').removeAttr('disabled');
            $("#edit_sms_tpl").show();
            w.open_close_btn(0);
            $("#editLnk").hide();
        } else {
            $("#prod_choice").hide().find('select').attr('disabled','disabled');
            $("#edit_sms_tpl").hide();

            //$("#preview").html(w.remove_link(defaultTpl));
            w.set_preview(w.remove_link(defaultTpl));
            //w.replace_var();

            $("#sms_content").html(defaultTpl);
            w.open_close_btn(1);
            $("#editLnk").show();
        }
    });
    $("#submit_post").on('click',function(){
//        $("#edit_sms_tpl").hide();
        if($("input[name='cformat']").val()=='') {
            alert('您没有修改短信模板内容无需保存');
            return false;
        }
        var t = $(this);
        t.attr('disabled','disabled').text('数据保存中...').next('#wait_img').show();
        $.post('/jq/jh/jh_front.php',$("form").serialize())
            .done(function(response){
                alert(response);
            })
            .always(function(){
                t.removeAttr('disabled').text('保存短信模板').next('#wait_img').hide();
//                $("#edit_sms_tpl").hide();
            });
    });
});


var pos;
function getPos()
{
    if(!!document.all){
        pos = document.selection.createRange();
    }else{
        pos = window.getSelection();
    }
}

function fn_insertPos(_text, _code){
    //console.log(_code);
    if(pos!=null) {
        if(!document.all){
            var range =pos.getRangeAt(0);
            range.deleteContents();
            var newP = document.createElement('span'),
                newL = document.createElement('a');
            newP.textContent = _text;
            newL.textContent = "X";
            newL.className = "del";
            newL.setAttribute('href','javascript:');
            newP.appendChild(newL);
            newP.setAttribute('contenteditable',false) ;
            newP.setAttribute('data-code',_code) ;
            range.insertNode(newP);
        } else {
            pos.pasteHTML('<span contenteditable="false" data-code="'+_code+'">'+_text+'<a href="javascript:" class="del">X</a></span>');
        }
        //释放位置
        pos=null;
    }
    else{
        alert("请选中文本框!");
    }
}

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',
        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

function CLen(curLength)
{
    var maxLen=67,
    //curLength = $("#content").val().length,
        sj = parseInt(curLength),
        arg =parseInt(sj/maxLen)+1;
    if(sj%maxLen==0)
    {
        arg =parseInt(sj/maxLen);
    }
    $("#CharLen").html('当前字符<font color=red>'+curLength+'</font>个,共<font color=red>'+arg+'</font>条计费.最大支持<font color=red>450</font>个字符.每条<font color=red>67</font>字计费');
    return arg;
}
